import { ElMessage } from 'element-plus';
import { useFetch, useRuntimeConfig } from 'nuxt/app';

const request = (options) => {
    const config = useRuntimeConfig();
    const BaseURL = config.public.baseURL;
    return new Promise((resolve, reject) => {
        useFetch(options.url, {
            baseURL: BaseURL,
            watch: false,
            onRequest({options}) {
                let token = "";
                if (import.meta.client) {
                    token = localStorage.getItem("token")
                }
                options.headers = {
                    token: token,
                    ...options.headers
                }
            },
            ...options
        }).then(res => {
            const responseBody = res.data.value;
            if (res.status.value == 'success') {
                resolve(responseBody);
            } else {
                reject(responseBody.message);
            }
        }).catch(err => {
            if (err.response.status == 429) {
                ElMessage.error('请求过于频繁，请稍后刷新');
            }
            reject(err)
        })
    })
}

export default request;